// pages/address/list/list.js
Page({
  data:{
    showDropdown: -1,
    addressList: [],
    statusBarHeight: getApp().globalData.statusBarHeight, // 状态栏高度
    navHeight: getApp().globalData.navHeight,       // 导航栏总高度
    tabBarHeight: getApp().globalData.tabBarHeight,  // 底部高度
  },

  onShow() { this.loadAddressList() },
  
  // 返回上一页
  navigateBack(delta = 1) { wx.navigateBack() },

  // 加载地址列表
  loadAddressList() {
    const list = wx.getStorageSync('addressList') || []
    this.setData({ addressList: list })
  },

  // 新建地址
  createNew() {
    wx.navigateTo({
      url: '/pages/address/edit/edit?type=new'
    })
  },
    // 新增方法
    closeDropdown() { this.setData({ showDropdown: -1 }); },
  
    // 阻止触摸滚动
    preventTouchMove() { return false; },
  
    // 阻止菜单点击冒泡
    stopPropagation() { return; },

  // 切换下拉菜单
  toggleDropdown(e) {
    const index = e.currentTarget.dataset.index;
    this.setData({
      showDropdown: this.data.showDropdown === index ? -1 : index
    });
  },

  // 编辑地址
  editAddress(e) {
    const index = e.currentTarget.dataset.index
    wx.navigateTo({
      url: `/pages/address/edit/edit?type=edit&index=${index}`
    })
    this.setData({ showDropdown: -1 }); // 隐藏下拉框
  },

  // 删除地址
  deleteAddress(e) {
    const id = e.currentTarget.dataset.id
    wx.showModal({
      title: '确认删除',
      content: '确定要删除该地址吗？',
      success: res => {
        if (res.confirm) {
          const list = this.data.addressList.filter(item => item.id !== id)
          wx.setStorageSync('addressList', list)
          this.loadAddressList()
        }
      }
    })
    this.setData({ showDropdown: -1 });  // 隐藏下拉框
  },
  //点击地址栏
  returnDefault(e){
    this.setDefault(e)  // 设置为默认值
    this.navigateBack() // 返回上一页
  },
  // 设置默认地址
  setDefault(e) {
    const id = e.currentTarget.dataset.id
    const list = this.data.addressList.map(item => ({
      ...item,
      isDefault: item.id === id
    }))
    wx.setStorageSync('addressList', list)
    this.loadAddressList()
    this.setData({showDropdown: -1});          // 后加的
    wx.showToast({title: '默认地址设置成功'});  // 后加的 
  },

  // 导入微信地址
  importWechat() {
    wx.chooseAddress({
      success: res => {
        const newAddress = this.formatWechatAddress(res)
        this.saveAddress(newAddress)
      },
      fail: err => this.handleAddressError(err)
    })
  },

  // 格式化微信地址
  formatWechatAddress(res) {
    return {
      id: Date.now().toString(),
      userName: res.userName,
      telNumber: res.telNumber,
      province: res.provinceName,
      city: res.cityName,
      county: res.countyName,
      detail: res.detailInfo,
      isDefault: false
    }
  },

  // 保存地址
  saveAddress(address) {
    const isExist = this.data.addressList.some(item => {
      // 提取比对字段（排除 id和isDefault）
      const { id: _, isDefault: __, ...restItem } = item;
      const { id, isDefault, ...restNewAddress } = address;
      // 比对字段数量和内容
      return Object.keys(restItem).length === Object.keys(restNewAddress).length 
        && Object.entries(restItem).every(([key, val]) => restNewAddress[key] === val);
    });
    if(!isExist){
      const list = [...this.data.addressList, address]
      wx.setStorageSync('addressList', list)
      this.loadAddressList()
    }else{
      wx.showToast({ title: '地址已经存在' })
    }
  },

  // 错误处理
  handleAddressError(err) {
    if (err.errMsg.includes('auth deny')) {
      wx.showModal({
        title: '需要地址权限',
        content: '请在设置中开启地址权限',
        success(res) {
          if (res.confirm) wx.openSetting()
        }
      })
    }
  }
})
